package system.config.aliyun.ram;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.sts20150401.AsyncClient;
import com.aliyun.sdk.service.sts20150401.models.AssumeRoleRequest;
import com.aliyun.sdk.service.sts20150401.models.AssumeRoleResponse;
import com.aliyun.sdk.service.sts20150401.models.AssumeRoleResponseBody;
import darabonba.core.client.ClientOverrideConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * 用于生成阿里云临时凭证角色
 *
 * @author 米泽鹏
 * @since 2024/1/12
 */
@Service
public class AssumeRoleService {

	@Value("${aliyun.ram.assumeRoleAccessKeyId}")
	private String accessKeyId;
	@Value("${aliyun.ram.assumeRoleAccessKeySecret}")
	private String accessKeySecret;

	public AssumeRoleResponseBody.Credentials generateCredentials(String roleArn, String roleSessionName, Long durationSeconds) {
		StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
				.accessKeyId(accessKeyId)
				.accessKeySecret(accessKeySecret)
				.build());

		AsyncClient client = AsyncClient.builder()
				.region("cn-beijing")
				.credentialsProvider(provider)
				.overrideConfiguration(ClientOverrideConfiguration.create().setEndpointOverride("sts.cn-beijing.aliyuncs.com"))
				.build();

		AssumeRoleRequest assumeRoleRequest = AssumeRoleRequest.builder()
				.roleArn(roleArn)
				.roleSessionName(roleSessionName)
				.durationSeconds(durationSeconds)
				.build();

		CompletableFuture<AssumeRoleResponse> assumeRoleResponseCompletableFuture = client.assumeRole(assumeRoleRequest);
		AssumeRoleResponse assumeRoleResponse;
		try {
			assumeRoleResponse = assumeRoleResponseCompletableFuture.get();
		} catch (InterruptedException | ExecutionException e) {
			throw new RuntimeException(e);
		} finally {
			client.close();
		}
		return assumeRoleResponse.getBody().getCredentials();
	}

}
